package com.wanghlme.bookstore.controller.admin;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wanghlme.bookstore.entity.Book;
import com.wanghlme.bookstore.service.BookService;
import com.wanghlme.bookstore.util.common.StringUtil;

import static com.wanghlme.bookstore.util.OperationStatusEnum.*;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RequestMapping("/admin/book")
@Controller("AdminBooksController")
public class BooksController {

    @Autowired
    private BookService bookService;

    @RequestMapping("/toInsertUI")
    public String toInsertUI() {
        log.info(Thread.currentThread().getStackTrace()[1].getMethodName());
        return "admin/book/insert";
    }

    @RequestMapping("/toUpdateUI")
    public String toUpdateUI() {
        log.info(Thread.currentThread().getStackTrace()[1].getMethodName());
        return "admin/book/update";
    }

    @RequestMapping(value = "/insert")
    @ResponseBody
    public String insert(@RequestBody Book book) {
        if (book == null) {
            return NULL.getValue();
        }
        log.debug("CurrentBook: {}", book.toString());
        return bookService.save(book) ? SUCCESS.getValue() : FAILURE.getValue();
    }

    @RequestMapping(value = "/listAll")
    @ResponseBody
    public String listAll(@RequestParam("page") String page) {
        if (StringUtil.isNullEmptyBlank(page)) {
            return "";
        }
        int index = Integer.parseInt(page);
        log.debug("CurrentPage: {}", index);
        Page<Book> pageModel = new Page<>(index, 10);
        pageModel.addOrder(OrderItem.asc("name"));
        Page<Book> pageResult = bookService.page(pageModel);
        List<Book> list = pageResult.getRecords();
        return "{\"pageNum\":" + pageResult.getPages() + "}," + JSON.toJSONString(list);
    }

    @RequestMapping(value = "/delete?id={delId}")
    @ResponseBody
    public String delete(@PathVariable("delId") String delId) {
        if (StringUtil.isNullEmptyBlank(delId)) {
            return NULL.getValue();
        }
        log.debug("CurrentID: {}", delId);
        return bookService.removeById(delId) ? SUCCESS.getValue() : FAILURE.getValue();
    }

    @RequestMapping(value = "/update")
    @ResponseBody
    public String update(@RequestBody Book book) {
        if (book == null) {
            return NULL.getValue();
        }
        log.debug("CurrentBook: {}", book.toString());
        return bookService.updateById(book) ? SUCCESS.getValue() : FAILURE.getValue();
    }
}
